import 'package:stacked/stacked.dart';
import '../heartbeat/blueprint/chat_model.dart';

/// 单聊协调器
class ChatCoordinator extends BaseViewModel {
  // 消息列表（模拟数据库）
  final List<ChatMessageModel> _messages = [];

  /// 获取所有消息
  List<ChatMessageModel> get messages => List.from(_messages);

  /// 初始化默认聊天数据
  void initializeDefaultChats() {
    _messages.clear();
    _messages.addAll(_getDefaultMessages());
  }

  /// 获取默认消息数据
  List<ChatMessageModel> _getDefaultMessages() {
    return [
      // admin用户与其他用户的聊天记录

      // admin ↔ Nexus (ID: 2)
      ChatMessageModel(
        id: '1',
        senderId: '1', // admin
        receiverId: '2', // Nexus
        content: 'Hey Nexus! How was your morning run today?',
        type: MessageType.text,
        createdAt: DateTime.now().subtract(const Duration(hours: 3)),
        isRead: true,
      ),
      ChatMessageModel(
        id: '2',
        senderId: '2', // Nexus
        receiverId: '1', // admin
        content:
            'It was amazing! Just finished a 10K in 45 minutes. The weather was perfect!',
        type: MessageType.text,
        createdAt: DateTime.now().subtract(
          const Duration(hours: 2, minutes: 45),
        ),
        isRead: true,
      ),
      ChatMessageModel(
        id: '3',
        senderId: '1', // admin
        receiverId: '2', // Nexus
        content:
            'That\'s impressive! I\'m planning to do a long run this weekend. Any route suggestions?',
        type: MessageType.text,
        createdAt: DateTime.now().subtract(
          const Duration(hours: 2, minutes: 30),
        ),
        isRead: true,
      ),
      ChatMessageModel(
        id: '4',
        senderId: '2', // Nexus
        receiverId: '1', // admin
        content:
            'The river trail is fantastic! It\'s about 15K and mostly flat. Perfect for a long run!',
        type: MessageType.text,
        createdAt: DateTime.now().subtract(
          const Duration(hours: 2, minutes: 15),
        ),
        isRead: true,
      ),

      // admin ↔ Vortex (ID: 3)
      ChatMessageModel(
        id: '5',
        senderId: '3', // Vortex
        receiverId: '1', // admin
        content: 'Hey! Are you free for a training session tomorrow?',
        type: MessageType.text,
        createdAt: DateTime.now().subtract(const Duration(days: 1, hours: 4)),
        isRead: true,
      ),
      ChatMessageModel(
        id: '6',
        senderId: '1', // admin
        receiverId: '3', // Vortex
        content: 'Sure! What time works for you?',
        type: MessageType.text,
        createdAt: DateTime.now().subtract(
          const Duration(days: 1, hours: 3, minutes: 45),
        ),
        isRead: true,
      ),
      ChatMessageModel(
        id: '7',
        senderId: '3', // Vortex
        receiverId: '1', // admin
        content:
            'How about 6 AM at the track? We can do some interval training!',
        type: MessageType.text,
        createdAt: DateTime.now().subtract(
          const Duration(days: 1, hours: 3, minutes: 30),
        ),
        isRead: true,
      ),
      ChatMessageModel(
        id: '8',
        senderId: '1', // admin
        receiverId: '3', // Vortex
        content: 'Perfect! See you there!',
        type: MessageType.text,
        createdAt: DateTime.now().subtract(
          const Duration(days: 1, hours: 3, minutes: 15),
        ),
        isRead: true,
      ),

      // admin ↔ Prism (ID: 4) - 包含拨打失败消息
      ChatMessageModel(
        id: '9',
        senderId: '1', // admin
        receiverId: '4', // Prism
        content:
            'Hey Prism! I tried calling you but it seems you\'re busy. Let me know when you\'re free!',
        type: MessageType.callFailed,
        createdAt: DateTime.now().subtract(
          const Duration(hours: 1, minutes: 30),
        ),
        isRead: false,
      ),
      ChatMessageModel(
        id: '10',
        senderId: '4', // Prism
        receiverId: '1', // admin
        content:
            'Sorry about that! I was in the middle of a marathon training session. What\'s up?',
        type: MessageType.text,
        createdAt: DateTime.now().subtract(const Duration(hours: 1)),
        isRead: true,
      ),
      ChatMessageModel(
        id: '11',
        senderId: '1', // admin
        receiverId: '4', // Prism
        content:
            'No worries! I wanted to ask about your new running shoes. How are they working out?',
        type: MessageType.text,
        createdAt: DateTime.now().subtract(const Duration(minutes: 45)),
        isRead: true,
      ),
      ChatMessageModel(
        id: '12',
        senderId: '4', // Prism
        receiverId: '1', // admin
        content:
            'They\'re fantastic! Great cushioning and very responsive. Perfect for long runs!',
        type: MessageType.text,
        createdAt: DateTime.now().subtract(const Duration(minutes: 30)),
        isRead: true,
      ),

      // admin ↔ Cipher (ID: 5)
      ChatMessageModel(
        id: '13',
        senderId: '5', // Cipher
        receiverId: '1', // admin
        content:
            'Hey! I saw your post about the marathon training. How\'s it going?',
        type: MessageType.text,
        createdAt: DateTime.now().subtract(const Duration(days: 2, hours: 2)),
        isRead: true,
      ),
      ChatMessageModel(
        id: '14',
        senderId: '1', // admin
        receiverId: '5', // Cipher
        content:
            'It\'s going great! I\'m up to 20K now. The training is tough but rewarding!',
        type: MessageType.text,
        createdAt: DateTime.now().subtract(
          const Duration(days: 2, hours: 1, minutes: 45),
        ),
        isRead: true,
      ),
      ChatMessageModel(
        id: '15',
        senderId: '5', // Cipher
        receiverId: '1', // admin
        content:
            'That\'s awesome! I remember my first marathon training. The key is consistency!',
        type: MessageType.text,
        createdAt: DateTime.now().subtract(
          const Duration(days: 2, hours: 1, minutes: 30),
        ),
        isRead: true,
      ),

      // admin ↔ Quantum (ID: 6) - 包含拨打失败消息
      ChatMessageModel(
        id: '16',
        senderId: '1', // admin
        receiverId: '6', // Quantum
        content:
            'I tried calling you but couldn\'t get through. Are you available for a quick chat?',
        type: MessageType.callFailed,
        createdAt: DateTime.now().subtract(const Duration(days: 1, hours: 6)),
        isRead: true,
      ),
      ChatMessageModel(
        id: '17',
        senderId: '6', // Quantum
        receiverId: '1', // admin
        content: 'Sorry! I was at the gym. What did you want to talk about?',
        type: MessageType.text,
        createdAt: DateTime.now().subtract(
          const Duration(days: 1, hours: 5, minutes: 30),
        ),
        isRead: true,
      ),
      ChatMessageModel(
        id: '18',
        senderId: '1', // admin
        receiverId: '6', // Quantum
        content:
            'I wanted to ask about your cross-training routine. Any tips for improving endurance?',
        type: MessageType.text,
        createdAt: DateTime.now().subtract(const Duration(days: 1, hours: 5)),
        isRead: true,
      ),
      ChatMessageModel(
        id: '19',
        senderId: '6', // Quantum
        receiverId: '1', // admin
        content:
            'Absolutely! I do swimming twice a week and cycling on rest days. It really helps!',
        type: MessageType.text,
        createdAt: DateTime.now().subtract(
          const Duration(days: 1, hours: 4, minutes: 45),
        ),
        isRead: true,
      ),

      // 其他用户之间的聊天记录

      // Nexus ↔ Vortex
      ChatMessageModel(
        id: '20',
        senderId: '2', // Nexus
        receiverId: '3', // Vortex
        content: 'Great run this morning! Your pace was incredible!',
        type: MessageType.text,
        createdAt: DateTime.now().subtract(const Duration(hours: 4)),
        isRead: true,
      ),
      ChatMessageModel(
        id: '21',
        senderId: '3', // Vortex
        receiverId: '2', // Nexus
        content:
            'Thanks! I\'ve been working on my speed training. It\'s paying off!',
        type: MessageType.text,
        createdAt: DateTime.now().subtract(
          const Duration(hours: 3, minutes: 45),
        ),
        isRead: true,
      ),

      // Prism ↔ Cipher
      ChatMessageModel(
        id: '22',
        senderId: '4', // Prism
        receiverId: '5', // Cipher
        content: 'Are you ready for the race this weekend?',
        type: MessageType.text,
        createdAt: DateTime.now().subtract(const Duration(days: 1, hours: 8)),
        isRead: true,
      ),
      ChatMessageModel(
        id: '23',
        senderId: '5', // Cipher
        receiverId: '4', // Prism
        content:
            'I\'m excited! The training has been intense but I feel ready!',
        type: MessageType.text,
        createdAt: DateTime.now().subtract(
          const Duration(days: 1, hours: 7, minutes: 30),
        ),
        isRead: true,
      ),

      // Cipher ↔ Quantum - 包含拨打失败消息
      ChatMessageModel(
        id: '24',
        senderId: '5', // Cipher
        receiverId: '6', // Quantum
        content:
            'I tried calling you but it went to voicemail. Let\'s meet up for a run tomorrow!',
        type: MessageType.callFailed,
        createdAt: DateTime.now().subtract(
          const Duration(hours: 2, minutes: 15),
        ),
        isRead: false,
      ),
      ChatMessageModel(
        id: '25',
        senderId: '6', // Quantum
        receiverId: '5', // Cipher
        content:
            'Sorry about that! I was in a meeting. Tomorrow sounds great! What time?',
        type: MessageType.text,
        createdAt: DateTime.now().subtract(
          const Duration(hours: 1, minutes: 45),
        ),
        isRead: true,
      ),
    ];
  }

  /// 发送文本消息
  Future<bool> dispatchTextMessage({
    required String senderId,
    required String receiverId,
    required String content,
  }) async {
    setBusy(true);
    try {
      if (content.trim().isEmpty) {
        setError('Message content cannot be empty');
        return false;
      }

      // 创建消息记录
      final message = ChatMessageModel(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        senderId: senderId,
        receiverId: receiverId,
        content: content.trim(),
        type: MessageType.text,
        createdAt: DateTime.now(),
      );

      _messages.add(message);
      notifyListeners();
      return true;
    } catch (e) {
      setError(e.toString());
      return false;
    } finally {
      setBusy(false);
    }
  }

  /// 发送拨打失败消息
  Future<bool> dispatchCallFailedMessage({
    required String senderId,
    required String receiverId,
    required String content,
  }) async {
    setBusy(true);
    try {
      if (content.trim().isEmpty) {
        setError('Message content cannot be empty');
        return false;
      }

      // 创建消息记录
      final message = ChatMessageModel(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        senderId: senderId,
        receiverId: receiverId,
        content: content.trim(),
        type: MessageType.callFailed,
        createdAt: DateTime.now(),
      );

      _messages.add(message);
      notifyListeners();
      return true;
    } catch (e) {
      setError(e.toString());
      return false;
    } finally {
      setBusy(false);
    }
  }

  /// 标记消息为已读
  Future<bool> markMessageAsRead(String messageId) async {
    setBusy(true);
    try {
      final messageIndex = _messages.indexWhere((msg) => msg.id == messageId);
      if (messageIndex == -1) {
        setError('Message not found');
        return false;
      }

      _messages[messageIndex] = _messages[messageIndex].copyWith(isRead: true);
      notifyListeners();
      return true;
    } catch (e) {
      setError(e.toString());
      return false;
    } finally {
      setBusy(false);
    }
  }

  /// 标记与特定用户的所有消息为已读
  Future<bool> markConversationAsRead({
    required String currentUserId,
    required String otherUserId,
  }) async {
    setBusy(true);
    try {
      for (int i = 0; i < _messages.length; i++) {
        final message = _messages[i];
        if ((message.senderId == otherUserId &&
                message.receiverId == currentUserId) &&
            !message.isRead) {
          _messages[i] = message.copyWith(isRead: true);
        }
      }

      notifyListeners();
      return true;
    } catch (e) {
      setError(e.toString());
      return false;
    } finally {
      setBusy(false);
    }
  }

  /// 获取与特定用户的聊天记录
  List<ChatMessageModel> fetchConversation({
    required String currentUserId,
    required String otherUserId,
  }) {
    return _messages
        .where(
          (message) =>
              (message.senderId == currentUserId &&
                  message.receiverId == otherUserId) ||
              (message.senderId == otherUserId &&
                  message.receiverId == currentUserId),
        )
        .toList()
      ..sort((a, b) => a.createdAt.compareTo(b.createdAt));
  }

  /// 获取用户的所有聊天列表（按最后消息时间排序）
  List<Map<String, dynamic>> fetchChatList(String userId) {
    final Map<String, ChatMessageModel> lastMessages = {};
    final Map<String, int> unreadCounts = {};

    // 找到每个对话的最后一条消息和未读数量
    for (final message in _messages) {
      String otherUserId;
      if (message.senderId == userId) {
        otherUserId = message.receiverId;
      } else if (message.receiverId == userId) {
        otherUserId = message.senderId;
      } else {
        continue;
      }

      // 更新最后一条消息
      if (!lastMessages.containsKey(otherUserId) ||
          message.createdAt.isAfter(lastMessages[otherUserId]!.createdAt)) {
        lastMessages[otherUserId] = message;
      }

      // 计算未读消息数量
      if (message.receiverId == userId && !message.isRead) {
        unreadCounts[otherUserId] = (unreadCounts[otherUserId] ?? 0) + 1;
      }
    }

    // 转换为列表并排序
    return lastMessages.entries
        .map(
          (entry) => {
            'otherUserId': entry.key,
            'lastMessage': entry.value,
            'unreadCount': unreadCounts[entry.key] ?? 0,
          },
        )
        .toList()
      ..sort(
        (a, b) => (b['lastMessage'] as ChatMessageModel).createdAt.compareTo(
          (a['lastMessage'] as ChatMessageModel).createdAt,
        ),
      );
  }

  /// 获取未读消息数量
  int getUnreadCount(String userId) {
    return _messages
        .where((message) => message.receiverId == userId && !message.isRead)
        .length;
  }

  /// 获取与特定用户的未读消息数量
  int getUnreadCountForUser({
    required String currentUserId,
    required String otherUserId,
  }) {
    return _messages
        .where(
          (message) =>
              message.senderId == otherUserId &&
              message.receiverId == currentUserId &&
              !message.isRead,
        )
        .length;
  }

  /// 删除消息
  Future<bool> removeMessage(String messageId, String userId) async {
    setBusy(true);
    try {
      final messageIndex = _messages.indexWhere((msg) => msg.id == messageId);
      if (messageIndex == -1) {
        setError('Message not found');
        return false;
      }

      final message = _messages[messageIndex];
      if (message.senderId != userId) {
        setError('You can only delete your own messages');
        return false;
      }

      _messages.removeAt(messageIndex);
      notifyListeners();
      return true;
    } catch (e) {
      setError(e.toString());
      return false;
    } finally {
      setBusy(false);
    }
  }

  /// 搜索消息
  List<ChatMessageModel> searchMessages({
    required String userId,
    required String keyword,
  }) {
    if (keyword.isEmpty) return [];

    return _messages
        .where(
          (message) =>
              (message.senderId == userId || message.receiverId == userId) &&
              message.content.toLowerCase().contains(keyword.toLowerCase()),
        )
        .toList()
      ..sort((a, b) => b.createdAt.compareTo(a.createdAt));
  }

  /// 删除与特定用户的所有对话
  Future<bool> deleteConversation({
    required String currentUserId,
    required String otherUserId,
  }) async {
    setBusy(true);
    try {
      _messages.removeWhere(
        (message) =>
            (message.senderId == currentUserId &&
                message.receiverId == otherUserId) ||
            (message.senderId == otherUserId &&
                message.receiverId == currentUserId),
      );
      notifyListeners();
      return true;
    } catch (e) {
      setError(e.toString());
      return false;
    } finally {
      setBusy(false);
    }
  }
}
